package 代码题.反射;

import java.lang.reflect.Field;

/**
 * 通过反射获取和设置私有字段的值
 */
public class SetPrivateField {
    public static void main(String[] args) {
        try {
            Class<?> c=Class.forName("代码题.反射.Test");
            Test t= (Test) c.newInstance();
            System.out.println(t);
            Field[] fields=c.getDeclaredFields();
            for (Field f:fields){
                if(f.getName().equals("name")){
                    f.setAccessible(true);
                    f.set(t,"快乐");
                    break;
                }
            }
            System.out.println(t);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}

class Test{
    public int age=18;
    private String name="哈哈";

    public void sayhello(){};

    private void saybad(){};

    @Override
    public String toString() {
        return "Test{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}